import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { Observable, Observer } from 'rxjs';
import { UploadService } from 'src/app/services/upload.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { PersonnelInfo } from 'src/app/models';
import { ActivatedRoute, Router } from '@angular/router';  // 用于获取路由参数
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { PersonnelService } from 'src/app/services/personnel.service';
import { OrganizationService } from 'src/app/services/organization.service';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
import { PageTitleService } from 'src/app/services/page-title.service';
@Component({
  selector: 'zepride-edit-personnel',
  templateUrl: './edit-personnel.component.html',
  styleUrls: ['./edit-personnel.component.less']
})
export class EditPersonnelComponent implements OnInit {
  validateForm: FormGroup;
  personnelInfo: PersonnelInfo = { orgTree: { parentId: '' }, acc: { password: '' }, gender: '男' } as PersonnelInfo;
  ImgUrl?: string;
  loading = false;
  logining = false;
  date = null;
  Id: string;
  departmentList: [];
  constructor(
    private fb: FormBuilder,
    private msg: NzMessageService,
    private route: Router,
    public uploadService: UploadService,
    private activatedRoute: ActivatedRoute,
    private personnelService: PersonnelService,
    private organizationService: OrganizationService,
    private phSvr: PageTitleService,
  ) {
    this.validateForm = this.fb.group({
      headerPhoto: [''],
      employeeNo: ['', [Validators.required]],
      name: ['', [Validators.required, Validators.pattern(/.*\S.*/)]],
      position: ['', [Validators.required]],
      gender: ['', [Validators.required]],
      parentId: ['', [Validators.required]],
      password: ['', [Validators.required]],
      birth: ['', [Validators.required]],
      idCard: ['', [Validators.required]],
      phone: ['', [Validators.required, Validators.pattern(/(^1\d{10}$)/)]],
    });
    //获取编辑需要的参数
    activatedRoute.queryParams.subscribe(queryParams => {
      this.Id = queryParams.Id;
      this.personnelInfo.orgTree.parentId = queryParams.parentId;
    });
    this.phSvr.setPageHeaderOption({
      title: '人员信息新建/编辑',
      subTitle: '用于人员信息新建/编辑',
    });
  }
  ngOnInit(): void {
    //查询部门列表
    this.getOrganizationTrees();
    if (this.Id != '0') {
      this.getOrganizationInfoById();
    }
  }
  //查询详情
  async getOrganizationInfoById() {
    try {
      const data = await this.personnelService.getUserInfoById(this.Id);
      this.personnelInfo = data;
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }
  goBack() {
    history.go(-1);
  }
  submitForm(value: { userName: string; phone: string; password: string; organizationalCode: string; address: string }): void {
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.msg.error('You can only upload JPG file!');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.msg.error('Image must smaller than 2MB!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  };

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }

  handleChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        this.loading = true;
        break;
      case 'done':
        this.getBase64(info.file!.originFileObj!, (img: string) => {
          this.loading = false;
          this.personnelInfo.headerPhoto = `${this.personnelService.uploadUrl}${info.file.response.fileUrl}`;
        });
        break;
      case 'error':
        this.msg.error('Network error');
        this.loading = false;
        break;
    }
  }
  onChange(result: Date): void {
    if (result && result instanceof Date) {
      this.personnelInfo.birth = result.getTime();
    }
  }


  //查询树
  async getOrganizationTrees() {
    try {
      const params = {
        objectName: ['Department', 'Organization']
      };
      const data = await this.organizationService.getOrganizationTrees(params);
      const dataList = data.map(v => {
        return {
          id: v.id,
          nodeName: v.nodeName,
        }
      });
      this.departmentList = dataList;
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }
  async confirm() {
    if (!this.validateForm.valid) return;
    if (this.logining) {
      return;
    }
    this.logining = true;

    try {
      if (this.Id != '0') {

        const data = await this.personnelService.updateUser(this.personnelInfo);
      } else {
        this.personnelInfo.status = '0'; //默认状态 正常
        const data = await this.personnelService.createUser(this.personnelInfo);
      }
      this.msg.success(this.Id != '0' ? '编辑人员成功' : '添加人员成功');
      history.go(-1);
    } catch (error) {
      ExceptionHandler.current.handleError(error);

    } finally {
      this.logining = false;
    }
  }
}
